package com.zhiyou.app.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.exception.SaTokenContextException;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.zhiyou.app.common.exception.UnAuthException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Slf4j
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    // 注册拦截器
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedHeaders("*")
                .allowedMethods("*")
                .maxAge(1800)
                .allowedOrigins("*");
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new MappingJackson2HttpMessageConverter());
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，打开注解式鉴权功能
        SaInterceptor saInterceptor = new SaInterceptor(handle -> {
            try {

                SaRouter.match("/**")    // 拦截的 path 列表，可以写多个 */
                        .notMatch("/sys/**")//系统服务全排除
                        // 下边的是knife4j使用的
                        .notMatch("/*.html")
                        .notMatch("/favicon.ico")
                        .notMatch("/swagger-resources/**")
                        .notMatch("/webjars/**")
                        .notMatch("/**/api-docs")
                        .notMatch("/user/maLogin")
                        .notMatch("/order/order4wRemain4Day")
                        .notMatch("/order/wxNotify")
                        .check(r -> {
                            String requestPath = SaHolder.getRequest().getRequestPath();
                            try {
                                StpUtil.checkLogin();
                            } catch (Exception e) {
                                log.warn("访问：{},登录校验失败:{}", requestPath, e.getMessage());
                                throw new UnAuthException();
                            }
                        });
            } catch (SaTokenContextException e) {
                log.info("satoken上下文异常");
            }
        });
        registry.addInterceptor(saInterceptor)
                .addPathPatterns("/**");
        ;
    }
}
